import 'dart:isolate';

import 'package:flutter/cupertino.dart';

/*
 * @Author: zhudaihao
 * @Date: 2022/3/6
 * @Describe: 创建isolate
 */



Future<MyIsolate> computeMyIsolate({Function(dynamic data)? success}) async {
  ReceivePort receivePort = ReceivePort();
  Isolate isolate = await Isolate.spawn(message, receivePort.sendPort);
  //监听结果
  receivePort.listen((message) {
    debugPrint('message:$message');
    if (message != null && success != null) {
      success(message);
    }
  });

  return MyIsolate(isolate, receivePort);
}

///返回结果
void message(SendPort sendPort) async {
  String date = sum(1000000000);
  sendPort.send(date);
}

///耗时任务：计算0到 num 数值的总和
String sum(int num) {
  int count = 0;
  while (num > 0) {
    count = count + num;
    num--;
  }
  return count.toString();
}

class MyIsolate {
  final Isolate? isolate;
  final ReceivePort? receivePort;

  MyIsolate(this.isolate, this.receivePort);

  void stop() {
    receivePort?.close();
    isolate?.kill(priority: Isolate.immediate);
    receivePort == null;
    isolate == null;
  }
}
